package com.star.markdown;

import org.commonmark.Extension;
import org.commonmark.ext.autolink.AutolinkExtension;
import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.ins.InsExtension;
import org.commonmark.node.IndentedCodeBlock;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.NodeRenderer;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlRenderer;
import org.commonmark.renderer.html.HtmlWriter;

import java.util.Collections;
import java.util.List;
import java.util.Set;

public class Markdown {
    public Markdown() {
    }

    public String parse(String text) {
        // 使用插件
        List<Extension> extensions = List.of(TablesExtension.create(),
                AutolinkExtension.create(),
                StrikethroughExtension.create(),
                InsExtension.create());

        Parser parser = Parser
                .builder()
                .extensions(extensions)
                .build();

        HtmlRenderer renderer = HtmlRenderer
                .builder()
                .extensions(extensions)
                .nodeRendererFactory(IndentedCodeBlockNodeRenderer::new)
                .build();

        Node node = parser.parse(text);
        return renderer.render(node);
    }

    private static class IndentedCodeBlockNodeRenderer implements NodeRenderer {
        private final HtmlWriter html;

        IndentedCodeBlockNodeRenderer(HtmlNodeRendererContext context) {
            this.html = context.getWriter();
        }

        @Override
        public Set<Class<? extends Node>> getNodeTypes() {
            return Collections.singleton(IndentedCodeBlock.class);
        }

        @Override
        public void render(Node node) {
            IndentedCodeBlock codeBlock = (IndentedCodeBlock) node;
            this.html.line();
            this.html.tag("pre");
            String literal = codeBlock.getLiteral();
            System.out.println(literal);
            this.html.text(literal);
            this.html.tag("/pre");
            this.html.line();
        }
    }

}